<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建专家' : "编辑专家" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="130px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="专家姓名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入专家姓名"></el-input>
        </el-form-item>

        <el-form-item label="专家职务" prop="expertPost">
          <el-input v-model="ruleForm.expertPost" placeholder="请输入专家职务"></el-input>
        </el-form-item>

        <el-form-item label="专家职称" prop="expertTitle">
          <el-input v-model="ruleForm.expertTitle" placeholder="请输入专家职称"></el-input>
        </el-form-item>

        <el-form-item label="专家类别" prop="expertType">
          <el-input v-model="ruleForm.expertType" placeholder="请输入专家类别"></el-input>
        </el-form-item>

        <el-form-item label="研究方向" prop="researchDirection">
          <el-input v-model="ruleForm.researchDirection" autosize type="textarea" placeholder="请输入研究方向"></el-input>
        </el-form-item>

        <el-form-item label="研究关键词" prop="researchKeyword">
          <el-input v-model="ruleForm.researchKeyword" autosize type="textarea" placeholder="请输入研究关键词"></el-input>
        </el-form-item>

        <el-form-item label="机构" prop="unit">
          <el-input v-model="ruleForm.unit" placeholder="请输入机构"></el-input>
        </el-form-item>

        <el-form-item label="成果总量" prop="totalAchievements">
          <el-input-number
            v-model="ruleForm.totalAchievements"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入成果总量"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="被引频次" prop="citedCount">
          <el-input-number
            v-model="ruleForm.citedCount"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入被引频次"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="H指数" prop="hIndex">
          <el-input-number
            v-model="ruleForm.hIndex"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入H指数"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="G指数" prop="gIndex">
          <el-input-number
            v-model="ruleForm.gIndex"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入G指数"
            :min="0"
          />
        </el-form-item>

         <el-form-item label="简介" prop="expertDesp">
          <el-input v-model="ruleForm.expertDesp" autosize type="textarea" placeholder="请输入简介"></el-input>
        </el-form-item>

        <el-form-item label="主学科" prop="subject">
          <el-input v-model="ruleForm.subject" placeholder="请输入主学科"></el-input>
        </el-form-item>

        <el-form-item label="核心期刊发文数" prop="achievementCoreCount">
          <el-input-number
            v-model="ruleForm.achievementCoreCount"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入核心期刊发文数"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="下载频次" prop="downloadCount">
          <el-input-number
            v-model="ruleForm.downloadCount"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入下载频次"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="标准一级代码" prop="unitId">
          <el-input v-model="ruleForm.unitId" placeholder="请输入标准一级代码"></el-input>
        </el-form-item>

        <el-form-item label="专家照片" prop="expertPic">
          <el-image style="width: 313px;"
            :src="imageUrl ? imageUrl : ''" fit="cover">
            <template #error>
              <div class="image-slot">
                <el-image style="width: 313px;" src="/images/expert_default.png" fit="cover" />
              </div>
            </template>
          </el-image>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadEvent">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传专家照片
          </el-button>
          <span style="margin-left: 10px;">请上传不超过10M的图片，格式：jpg/png/jpeg</span>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "backendExpertInfoAdd" }
</script>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { uploadFile } from '@/utils/file.js'
import { testFileType, testFileSize, isJsonString } from '@/utils/backend.js'
import { ContentTypeEnum } from '@/enums/httpEnum';
import { useSystemStore } from '@/stores/modules/system.js';

/* 路由 */
const route = useRouter()

const systemStore = useSystemStore()

onMounted(() => {
  if(route.currentRoute.value.query.id){
    getExpertInfoDetail()
  }
})

/* 处理图片路径 */
const getImagePath = (val) => {
  let str = ""
  let file = JSON.parse(val)

  if(!file.filePathArray) return str

  if(file.filePathArray.length == 1) {
    str = file.filePathArray[0].CompleteFilePath.substring(1)
  }
  return str
}

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getExpertInfoDetail = () => {
  loading.value = true
  http.$GET("/TheoryStudyM/GetExpertInfoDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return

    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })

    /* 处理数值 */
    ruleForm.value.totalAchievements = Number(res.result.totalAchievements)
    ruleForm.value.citedCount = Number(res.result.citedCount)
    ruleForm.value.hIndex = Number(res.result.hIndex)
    ruleForm.value.gIndex = Number(res.result.gIndex)
    ruleForm.value.achievementCoreCount = Number(res.result.achievementCoreCount)
    ruleForm.value.downloadCount = Number(res.result.downloadCount)

    /* 专家图片路径 */
    /* if(!isJsonString(res.result.expertPic)){
      imageUrl.value = ""
      ruleForm.value.expertPic = ""
      return
    } */
    if(res.result.expertPic != ''){
      /* let picture = JSON.parse(res.result.expertPic) */

      imageUrl.value = `${systemStore.frontHost}/TpwpExpertStatic/${res.result.unitId}/${isJsonString(res.result.expertPic) ? getImagePath(res.result.expertPic) : res.result.expertPic}`

      /* if(picture.filePathArray){
        imageUrl.value = import.meta.env.VITE_APP_STATIC_URL + picture.filePathArray[0].CompleteFilePath
      }else{
        imageUrl.value = ""
        ruleForm.value.expertPic = ""
      } */
    } else {
      imageUrl.value = ""
      ruleForm.value.expertPic = ""
    }
  })
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 表单数据 */
const ruleForm = ref({
  id: "",
  name: "",
  expertPost: "",
  expertTitle: "",
  expertType: "",
  researchDirection: "",
  researchKeyword: "",
  unit: "",
  totalAchievements: null,
  citedCount: null,
  hIndex: null,
  gIndex: null,
  expertDesp: "",
  subject: "",
  achievementCoreCount: null,
  downloadCount: null,
  unitId: null,
  expertPic: "",
})

/* 封面图片路径 */
const imageUrl = ref(null)
/* 是否有上传图片 */
const isUploadImage = ref(false)

/* 上传文件校验 */
const checkFile = (rule, value, callback) => {
  if (!ruleForm.value.expertPic) {
    callback(new Error('请上传专家图片'))
  } else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  name: [
    { required: true, message: '请填写专家姓名', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  expertTitle: [
    { required: true, message: '请填写专家职称', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  expertPost: [
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  expertType: [
    { required: true, message: '请填写专家类别', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  researchDirection: [
    { required: true, message: '请填写研究方向', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  researchKeyword: [
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  unit: [
    { required: true, message: '请填写机构', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  expertDesp: [
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  subject: [
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  /* totalAchievements: [
    { required: true, message: '请填写成果总量', trigger: 'blur' }
  ],
  citedCount: [
    { required: true, message: '请填写被引频次', trigger: 'blur' }
  ],
  hIndex: [
    { required: true, message: '请填写H指数', trigger: 'blur' }
  ],
  gIndex: [
    { required: true, message: '请填写G指数', trigger: 'blur' }
  ],
  expertDesp: [
    { required: true, message: '请填写简介', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请填写主学科', trigger: 'blur' }
  ],
  achievementCoreCount: [
    { required: true, message: '请填写achievementCoreCount', trigger: 'blur' }
  ],
  downloadCount: [
    { required: true, message: '请填写下载频次', trigger: 'blur' }
  ],
  unitId: [
    { required: true, message: '请填写标准一级代码', trigger: 'blur' }
  ], */
  /* expertPic: [
    { required: true, validator: checkFile, message: '请上传附件', trigger: 'change' }
  ], */
})

/* 点击上传文件 */
const uploadEvent = () => {

  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"

  uploadFile({ accept: fileType }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG)$/)){
      ruleForm.value.expertPic = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }
    /* 文件大小判断 */
    if(!testFileSize(res, 10*1024*1024)){
      ruleForm.value.expertPic = ""
      imageUrl.value = ""
      isUploadImage.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res[0]){
      isUploadImage.value = true
      ruleForm.value.expertPic = res[0]
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate('expertPic')
      /* 预览缩略图 */
      var reader = new FileReader()
      reader.onload = function(e) {
        imageUrl.value = e.target.result
      }
      reader.readAsDataURL(res[0])
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交表单 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 未更新图片时不传值 */
      if(!isUploadImage.value) {
        delete ruleForm.value.expertPic
      }

      http.$POST("/TheoryStudyM/AddOrUpdateExpertInfo", {...ruleForm.value}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage({
            type: 'warning',
            message: '操作失败',
          })
        }else{
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          route.push({
            path: "/backend/expert-info"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage({
          type: 'warning',
          message: '操作失败',
        })
      })
    }else{
      ElMessage({
        type: 'warning',
        message: '请先完成必填项',
      })
    }
  })
}

/* 重置表单 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  imageUrl.value = ""
  isUploadImage.value = false
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/expert-info",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>